import { HttpMethod } from "../NetConfig";
import BaseService from "./BaseService";


export default class WebHttpService extends BaseService {

    private static OK = 4;
    isReady() {
        return true;
    }

    connect() {

        this.onOpen();
    }
    sendData(message: net.SendMessage) {
        let xhr = this.createXHR();
        let protoID = message.sendData.protoId
        let address = this.url;
        let self = this
        xhr.timeout = 15000;
        xhr.ontimeout = function () {
            self.onError(message);
        }
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 400) {
                var data = xhr.responseText;
                self.onData(data);
            } else {
                self.onError(message);
            }
        };
        let data = message.data
        let method = message.sendData.method

        if (method == HttpMethod.GET) {
            address = address + protoID + "?" + data;
            xhr.open(method, address);
            try {
                xhr.send();
            } catch (error) {
                console.log("get  error ", error);
            }

        } else {
            // post请求
            xhr.open(method, address + protoID);
            try {
                xhr.send(data);
            } catch (error) {
                console.log("post  error ", error);
            }

        }
    }

    createXHR() {
        // IE7+,Firefox, Opera, Chrome ,Safari
        return new XMLHttpRequest();
    }

}
